$(function () {
  let token = null
  //获取token值
  async function denglu() {
    const data = await axios.post('http://124.223.14.236:3001/api/user/login', {
      username: "tv",
      password: "123456"
    })
    token = data.data.data.token
  } denglu()


  let searchList = document.querySelector('.history-list ul ')

  清空历史记录
  $('.del').on('click', function () {
    searchList.innerHTML = ''
  })


  //开始默认历史为空
  searchList.innerHTML = ''

  //封装分类渲染函数
  async function fn(url) {
    const data = await axios.get(url)
    const lists = data.data.data.list
    console.log(lists);
    let htmlStr = lists.map((element) => {
      return `
                      <li data-id='${element.id}' id='${element.cate_id}'>
                          <img src="${element.img}" alt="">
                            <h3>${element.title}</h3>
                              <p>
                                  <span class="price">￥${(element.price) / 100}</span>
                                  <span class="add" data-price='${(element.price) / 10}'>+</span>
                              </p>
                       </li>
                         `
    }).join('')
    document.querySelector('.good-list ul').innerHTML = htmlStr
    fnsAdd()
  } fn(`http://124.223.14.236:3001/api/goods`)


  //添加商品到购物车
  function fnsAdd() {
    const list = document.querySelectorAll('.add')
    const liAll = document.querySelectorAll('.good-list li')
    for (let i = 0; i < list.length; i++) {
      list[i].addEventListener('click', async function () {
        var data = {
          title: liAll[i].children[1].innerHTML,
          img: liAll[i].children[0].src,
          price: +list[i].dataset.price,
          goods_id: +liAll[i].dataset.id,
          cate_id: +liAll[i].id,
          buy_num: 1,
          is_selected: 1,
        }
        const res = await axios.post('http://124.223.14.236:3001/api/cart/create', data, {
          headers: {
            Authorization: token
          }
        })
        if (res.status !== 200) return alert(res.statusText)
        alert(res.data.msg)
      })
    }
  }






  //添加搜索功能
  $('.text').on('click', async function () {
    const searchText = $('input').val().trim()
    if (searchText.length > 0) {
      const li = document.createElement('li')
      li.innerHTML = searchText
      searchList.appendChild(li)
      const { data: { data } } = await axios.get('http://124.223.14.236:3001/api/goods/cate')
      data.map((element, i) => {
        if (searchText === element.name) {
          console.log(i);
          fn(`http://124.223.14.236:3001/api/goods?cate_id=${i + 1}`)
        }
        else {
          document.querySelector('.good-list ul').innerHTML = ""
        }
      })

    }
  })

})